<template>
  <div class="app-container">
    <el-form
      :model="queryEquipmentParams"
      ref="queryForm"
      :inline="true"
      label-width="70px"
    >
      <el-form-item label="设备ID" prop="equipmentId">
        <el-input
          v-model="queryEquipmentParams.equipmentId"
          placeholder="设备ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryEquipmentParams.equipmentName"
          placeholder="设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row>
      <el-col :span="4">
        <el-table
          :cell-style="{ padding: this.tablePadding }"
          ref="equipmentTable"
          :data="equipmentList"
          :height="tableHeight"
          highlight-current-row
          @current-change="handleCurrentEquipmentChange"
          border
        >
          <template slot="empty">
            <div>
              <span>设备不存在</span>
            </div>
          </template>
          <el-table-column label="设备ID" align="center" prop="equipmentId" />

          <el-table-column
            label="设备名称"
            align="center"
            prop="equipmentName"
          />
        </el-table>

        <pagination
          v-show="equipmentTotal > 0"
          small
          layout="prev, pager, next"
          :total="equipmentTotal"
          :page.sync="queryEquipmentParams.pageNum"
          :limit.sync="queryEquipmentParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="20">
        <div class="video-container">
          <div class="preview-content">
            <video
              id="remote-video"
              ref="remoteVideo"
              width="850"
              height="350"
              autoplay
              muted
              playsinline
              controls
            ></video>
            <div>
              <!-- 按钮些 -->
            </div>
          </div>
        </div>
        <div class="txt-box">
          <div class="display-flex">
            <div class="center-width">
              <div>设备状态：{{ setStatus(parseInt(info.equipmentType)) }}</div>
              <el-tooltip
                :disabled="String(info.taskName).length < 5"
                :content="info.taskName"
                placement="top"
              >
                <div class="more-txt">当前任务：{{ info.taskName }}</div>
              </el-tooltip>
              <el-tooltip
                :disabled="String(info.taskQuantity).length < 5"
                :content="String(info.taskQuantity)"
                placement="top"
              >
                <div>零件层厚：{{ info.thickness }} <span class="num-bai" style="margin-left:5px">mm</span></div>
              </el-tooltip>
              <div>
                加工进度：
                <span
                  :style="{
                    color: info.currentLayerFinished > 0 ? '#1890FF' : '',
                  }"
                  >{{ info.currentLayerFinished }}</span
                >/{{ info.detail }}
                <span class="num-bai">（层）</span>
              </div>
              <div>剩余时间：{{ second }}</div>
              <el-progress
                :text-inside="true"
                :stroke-width="22"
                :percentage="parseFloat(info.productionStatus)"
              ></el-progress>
            </div>
            <div style="line-height: 30px; margin-left: 150px" class="flex: 1;">
              <div><span style="width:14px;display:inline-block"></span>氧含量：{{ info.oxygen }}%</div>
              <div>舱室压力：{{ info.cabinPressure }}mbar</div>
              <div>滤网压差：{{ info.filterPressureDiff }}mbar</div>
              <div>风机流速：{{ info.fanFlux }}m/s</div>
              <div>基板温度：{{ info.buildCylinderTemperature }}℃</div>
              <div>管道温度：{{ info.fanPipeTemp }}℃</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listEquipment } from "@/api/equipment/param";
import { ZegoExpressEngine } from "zego-express-engine-webrtc";
import { getZegoToken } from "@/api/base/unit";
import socket from "../../../websocketMixins";
import { formatSeconds } from "@/utils/index";
const config = require("@/utils/configId");
export default {
  mixins: [socket],
  data() {
    return {
      zg: null,
      equipmentList: [],
      equipmentTotal: 0,
      loading: false,
      tableHeight: window.innerHeight - 220,
      queryEquipmentParams: {
        pageNum: 1,
        pageSize: 10,
        status: 1,
      },
      info: {
        equipmentType: null,
        taskName: "",
        taskQuantity: "",
        thickness:0,
        currentLayerFinished: 0,
        detail: 0,
        productionStatus: 0,
        oxygen: null,
        cabinPressure: null,
        filterPressureDiff: null,
        fanFlux: null,
        buildCylinderTemperature: null,
        fanPipeTemp: null,
      },
      second: null,
      address: null,
      statusOptions: [],
      remainingSave: 0,
      timer: null,
    };
  },
  created() {
    this.getData()
    // 设备状态
    this.getDicts("equipment_info_status").then((response) => {
      this.statusOptions = response.data;
    });
  },

  mounted() {
    this.$nextTick(() => {
      this.initWebSocket();
    });
  },
  destroyed() {
        //页面销毁时关闭长连接
        this.websocketclose();
        this.zg.logoutRoom(window.localStorage.getItem("DICS_userId"))
    },
  methods: {
    websocketonmessage(msg) {
      //数据接收
      let obj = msg.data;
      if (obj.indexOf("room") !== -1) {
        let res = JSON.parse(obj);
        if (res.id == this.address) {
          if (res.room == 1) {
            this.info.productionStatus = this.toPercent(res.productionStatus);
            this.info.detail = res.detail; //当前任务总层数
            this.info.currentLayerFinished = res.currentLayerFinished; //当前任务打印层数
          } else if (res.room == 2) {
            //任务名称
            this.info.thickness=res.thickness
            this.info.taskName = res.taskName;
          } else if (res.room == 0) {
            //设备状态,排队任务
            this.info.equipmentType = res.equipmentType;
            this.info.taskQuantity = res.taskQuantity ? res.taskQuantity : "";
          } else if (res.room == 4) {
            this.info.remaining = res.remaining;

            this.second = this.formatSeconds(this.remainingSave);
            clearInterval(this.timer);
            let _this = this;
            this.timer = setInterval(() => {
              _this.remainingSave = parseFloat(_this.remainingSave) - 1;
              if (_this.remainingSave == -1||_this.remainingSave<-1) {
                clearInterval(_this.timer);
                return;
              }
              _this.second = _this.formatSeconds(_this.remainingSave);
            }, 1000);
          } else if (res.room == 5) {
            //报警
            this.info.alramDataNum = res.alramDataNum;
          } else if (res.room == 3) {
            //气氛参数
            [
              "oxygen",
              "cabinPressure",
              "filterPressureDiff",
              "fanFlux",
              "buildCylinderTemperature",
              "fanPipeTemp",
            ].forEach((key) => {
              if (key in res) {
                this.info[key] = res[key];
              }
            });
          } else if (res.room == 6) {
            this.info.taskStatus = res.taskStatus; //任务状态
          }
        }
      }
      this.reset();
    },
    toPercent(point) {
      var str = Number(point * 100).toFixed(2);
      // str+="%";
      return str;
    },
    setStatus(status) {
      return this.selectDictLabel(this.statusOptions, status);
    },
    async handleCurrentEquipmentChange(selection) {
      if (selection != null) {
        if (this.address) {
          await this.zg.stopPlayingStream(this.address);
        }
        this.address = selection.address;
        this.websocketsend(selection.address);
        this.setDetails(selection); //处理设备详情
        const remoteStream = await this.zg.startPlayingStream(this.address);
        // remoteVideo 为本地 <video> 或 <audio> 对象
        this.$refs["remoteVideo"].srcObject = remoteStream;
      }
    },
    setDetails(res) {
      this.info.productionStatus = this.toPercent(res.productionStatus);
      this.info.detail = res.detail; //当前任务总层数
      this.info.currentLayerFinished = res.currentLayerFinished; //当前任务打印层数
      //任务名称
      this.info.taskName = res.taskName;
      //设备状态,排队任务
      this.info.equipmentType = res.equipmentType;
      this.info.taskQuantity = res.taskQuantity ? res.taskQuantity : "";
      this.info.thickness=res.thickness
      this.info.remaining = res.remaining;

      this.second = this.formatSeconds(this.remainingSave);
      clearInterval(this.timer);
      let _this = this;
      this.timer = setInterval(() => {
        _this.remainingSave = parseFloat(_this.remainingSave) - 1;
        if (_this.remainingSave == -1||_this.remainingSave<-1) {
          _this.remainingSave=0
          clearInterval(_this.timer);
          return;
        }
        _this.second = _this.formatSeconds(_this.remainingSave);
      }, 1000);
      //气氛参数
      [
        "oxygen",
        "cabinPressure",
        "filterPressureDiff",
        "fanFlux",
        "buildCylinderTemperature",
        "fanPipeTemp",
      ].forEach((key) => {
        if (key in res) {
          this.info[key] = res[key];
        }
      });
      this.info.taskStatus = res.taskStatus; //任务状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryEquipmentParams.pageNum = 1;
      // this.paramList = [];//注意处理右边数据！！！！！！！！！！
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryEquipmentParams.equipmentName = null;
      this.queryEquipmentParams.equipmentId = null;

      this.handleQuery();
    },
    getList() {
      this.loading = true;
      listEquipment(this.queryEquipmentParams).then((response) => {
        this.equipmentList = response.rows;
        this.address = this.equipmentList[0].address;
        this.equipmentTotal = response.total;
        this.loading = false;
      });
    },
    // 连接成功后

    websocketOpenSuccess() {
      let _this = this;
      setTimeout(() => {
        _this.$refs.equipmentTable.setCurrentRow(_this.equipmentList[0]);
      }, 2000);
    },
    getData() {
      // 文档中的 js 示例代码可粘贴至此处
      // 项目唯一标识 AppID，Number 类型，请从 ZEGO 控制台获取
      let appID = config.appID;
      // 接入服务器地址 Server，String 类型，请从 ZEGO 控制台获取（获取方式请参考上文“前提条件”）
      let server = config.zegoServer;

      // 初始化实例
      this.zg = new ZegoExpressEngine(appID, server);

      // 房间状态更新回调
      // 此处在登录房间成功后，立即进行推流。在实现具体业务时，您可选择其他时机进行推流，只要保证当前房间连接状态是连接成功的即可。
      // 房间状态更新回调
      this.zg.on(
        "roomStateUpdate",
        async (roomID, state, errorCode, extendedData) => {
          if (state == "CONNECTED") {
            console.log(
              "与房间连接成功，只有当房间状态是连接成功时，才能进行推流、拉流等操作111111111111。"
            );
            // 与房间连接成功，只有当房间状态是连接成功时，才能进行推流、拉流等操作。
            // 创建流、预览
            // 调用 createStream 接口后，需要等待 ZEGO 服务器返回流媒体对象才能执行后续操作
            // const localStream = await this.zg.createStream();
            // 获取页面的 video 标签
            //  const localVideo = document.getElementById("local-video");
            // stream 为MediaStream对象，开发者可通过赋值给video或audio的srcObject属性进行渲染
            // this.$refs['localVideo'].srcObject = localStream;
            // 开始推流，将自己的音视频流推送到 ZEGO 音视频云，此处 streamID 由用户定义，需全局唯一
           
          }
        }
      );
      // 登录房间，成功则返回 true
      // userUpdate 设置为 true 才能收到 roomUserUpdate 回调。
      let userID = window.localStorage.getItem("DICS_userId"); // userID 用户自己设置，必须保证全局唯一
      let userName = "这是名字"; // userName 用户自己设置，没有唯一性要求
      let roomID = window.localStorage.getItem("DICS_userId"); // roomID 用户自己设置，必须保证全局唯一
      // 请填写您获取到的 token，字符串类型
      getZegoToken({
        appId: String(appID),
        secretKey: config.zegoSecretKey,
        userId: userID,
        roomId: roomID,
      }).then((res) => {
        let token = res.data;
        this.zg
          .loginRoom(
            roomID,
            token,
            { userID, userName: userID },
            { userUpdate: true }
          )
          .then((result) => {
            this.getList();
            console.info(
              '"login success成功了啊"',
              result
            );
            if (result == true) {
              console.log(
                "login success成功了啊！！！！！！！！！！！！！！！"
              );
            }
          });
      })
    },
  },
};
</script>

<style>
.video-container {
  padding: 0 15px;
}

.center-width {
  line-height: 30px;
  width: 210px;
  margin-left: 20px;
}
.txt-box {
  padding-top: 20px;
}
#remote-video {
  background: #000;
}
</style>